package grid;

import graph.HasGraph;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Vector;

public class GridGraph implements HasGraph {
	
	public Object[] allCells;

	int[][] coords;

	// int -1 =no Nb;
	
	public Vector<Integer>[] nbs;

	public int nX;

	public int nY;

	public int n;
	
	
public GridGraph(){
	
}
	public  GridGraph(Object[] cells,int nX,int nY) {
		this.nX = nX;
		this.nY = nY;
		n=cells.length;
		allCells = cells;
		coords = new int[n][2];
		nbs = new Vector[n];
		int i = 0;
		for (int x = 0; x < nX; x++) {
			for (int y = 0; y < nY; y++) {
				//allCells[i] = cells[x][y];
				coords[i][0] = x;
				coords[i][1] = y;
				nbs[i] = get8Nbs(x, y);
				i++;
			}
		}
	}
	
	public Vector<Integer> get4Nbs(int x, int y) {
		Vector<Integer> nbs = new Vector<Integer>();
		Integer nb;
		nb = getIndex(x + 1, y);
		if (nb != null) {
			nbs.add(nb);
		}
		nb = getIndex(x, y + 1);
		if (nb != null) {
			nbs.add(nb);
		}
		nb = getIndex(x - 1, y);
		if (nb != null) {
			nbs.add(nb);
		}
		nb = getIndex(x, y - 1);
		if (nb != null) {
			nbs.add(nb);
		}
		return nbs;
	}
	public Vector<Integer> get8Nbs(int i) {
		return get8Nbs(getX(i),getY(i));
	}
	public Vector<Integer> get8Nbs(int x, int y) {
		Vector<Integer> nbs = new Vector<Integer>();
		Integer nb;
		nb = getIndex(x + 1, y);
		if (nb != null) {
			nbs.add(nb);
		}
		nb = getIndex(x + 1, y + 1);
		if (nb != null) {
			nbs.add(nb);
		}
		nb = getIndex(x, y + 1);
		if (nb != null) {
			nbs.add(nb);
		}
		nb = getIndex(x - 1, y + 1);
		if (nb != null) {
			nbs.add(nb);
		}
		nb = getIndex(x - 1, y);
		if (nb != null) {
			nbs.add(nb);
		}
		nb = getIndex(x - 1, y - 1);
		if (nb != null) {
			nbs.add(nb);
		}
		nb = getIndex(x, y - 1);
		if (nb != null) {
			nbs.add(nb);
		}
		nb = getIndex(x + 1, y - 1);
		if (nb != null) {
			nbs.add(nb);
		}
		return nbs;
	}

	
	
	public Integer getIndex(int x, int y) {
		if (x < 0 || x >= nX)
			return null;
		if (y < 0 || y >= nY)
			return null;
		
		return x  * nY + y;
	}
	public int getX(int i){
		return i/nY;
	}
	public int getY(int i){
		return i%nY;
	}

	public int getNodesSize() {
		// TODO Auto-generated method stub
		return n;
	}

	public Object getNode(int i){
		return allCells[i];
	}


	public double getWeight(int n1, int n2) {
		int[] c1 = coords[n1];
		int[] c2 = coords[n2];
		if (c1[0] == c2[0] || c1[1] == c2[1])
			return 1;
		return 1.4;
	}

	public Iterator<Integer> getNeighbourIterator(int i) {
		Vector<Integer> nb = (Vector<Integer>)nbs[i];
		return nb.iterator();
	}
	

	
	public int[] getNeighbours(int i) {
		// TODO Auto-generated method stub
		return null;
	}
}
